package com.demo.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class AIOTimeServer implements IServer {

	private static final Charset charset = StandardCharsets.UTF_8;

	@Override
	public void bootStrap() throws Exception {
		AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(4));
		AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group)
				.bind(new InetSocketAddress(8888));
		server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
			@Override
			public void completed(AsynchronousSocketChannel result, Void attachment) {
				server.accept(null, this); // 接受下一个连接
				try {
					String now = new Date().toString();
					ByteBuffer buffer = ByteBuffer.wrap((now + "\r\n").getBytes(charset));
					// result.write(buffer, null, new
					// CompletionHandler<Integer,Void>(){...}); //callback or
//					buffer.flip();
					Future<Integer> f = result.write(buffer);
					System.out.println(f.get());
					System.out.println("sent to client: " + now);
					result.close();
				} catch (IOException | InterruptedException | ExecutionException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void failed(Throwable exc, Void attachment) {
				exc.printStackTrace();
			}
		});
		group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

	}

	@Override
	public void shutDown() {
		// TODO Auto-generated method stub

	}

}
